頁面畫完後,因為我們要資料綁定的關係,所以要對 Layout 做一些改變
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.5.1"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1"
如果不需要 Context,可以繼承 ViewModel()
class NoteViewModel: ViewModel() {
init {
Log.d("maho", "ViewModel")
}
override fun onCleared() {
super.onCleared()
Log.d("maho", "NoteViewModel onCleared")
}
}
如果需要 Context,可以繼承 AndroidViewModel(application),用getApplication<Application>()
class NoteViewModel(application: Application): AndroidViewModel(application) {
init {
Log.d("maho", "NoteViewModel")
}
override fun onCleared() {
super.onCleared()
Log.d("maho", "NoteViewModel onCleared")
}
}
android {
buildFeatures {
dataBinding true
}
}
CoordinatorLayout
改成layout
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>
<data>
,然後增加剛剛新增的NoteViewModel
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="NoteViewModel"
type="com.example.hacknote.note.NoteViewModel" />
</data>
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>